<template>
  <div class="spec-preview" @mousemove="specMove">
    <img :src="url || skuDefaultImg" />
    <div class="event"></div>
    <div class="big">
      <img :src="url || skuDefaultImg" ref="bigImg" />
    </div>
    <div class="mask" ref="mask"></div>
  </div>
</template>

<script>
export default {
  name: 'Zoom',
  props: ['skuDefaultImg'],
  data() {
    return {
      url: this.skuDefaultImg,
    }
  },
  mounted() {
    //需要底部点击图片时,携带数据传输到当前组件,并修改Url值
    // 使用事件总线实现
    this.$bus.$on('getUrl', (url) => {
      this.url = url
    })
  },
  methods: {
    // 创建移动函数,使得可以同步移动放大镜和隔壁大图
    specMove(e) {
      let mask = this.$refs.mask
      let bigImg = this.$refs.bigImg
      // e.offsetX为当前事件的左边距离,pageX为整个页面,clientX为当前视口
      let spaceDistance = {
        x: e.offsetX,
        y: e.offsetY,
      }
      let maskMove = {
        x: spaceDistance.x - mask.offsetWidth / 2,
        y: spaceDistance.y - mask.offsetHeight / 2,
      }
      // 设置边界
      if (maskMove.x <= 0) {
        maskMove.x = 0
      } else if (maskMove.x >= e.target.clientWidth - mask.offsetWidth) {
        maskMove.x = e.target.clientWidth - mask.offsetWidth
      }
      if (maskMove.y <= 0) {
        maskMove.y = 0
      } else if (maskMove.y >= e.target.clientHeight - mask.offsetHeight) {
        maskMove.y = e.target.clientHeight - mask.offsetHeight
      }
      // 让mask遮罩跟随移动,并保证鼠标一直在mask中间
      mask.style.left = maskMove.x + 'px'
      mask.style.top = maskMove.y + 'px'
      bigImg.style.left = -maskMove.x * 2 + 'px'
      bigImg.style.top = -maskMove.y * 2 + 'px'
    },
  },
}
</script>

<style lang="less">
.spec-preview {
  position: relative;
  width: 400px;
  height: 400px;
  border: 1px solid #ccc;

  img {
    width: 100%;
    height: 100%;
  }

  .event {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 998;
  }

  .mask {
    width: 50%;
    height: 50%;
    background-color: rgba(0, 255, 0, 0.3);
    position: absolute;
    left: 0;
    top: 0;
    display: none;
  }

  .big {
    width: 100%;
    height: 100%;
    position: absolute;
    top: -1px;
    left: 100%;
    border: 1px solid #aaa;
    overflow: hidden;
    z-index: 998;
    display: none;
    background: white;

    img {
      width: 200%;
      max-width: 200%;
      height: 200%;
      position: absolute;
      left: 0;
      top: 0;
    }
  }

  .event:hover ~ .mask,
  .event:hover ~ .big {
    display: block;
  }
}
</style>
